#include "game.h"

const sf::Time Game::TimePerFrame = sf::seconds(1.f/60.f);

Game::Game()
{
	mWindow.create(sf::VideoMode(800, 600), "Tanks");
	mWindow.setFramerateLimit(100);

	mStaticNumFrames = 0;
	mFont.loadFromFile("Czcionki/House Of Fun.TTF");
	mStatisticsText.setFont(mFont);
	mStatisticsText.setPosition(630,10);
}

void Game::run()
{
	sf::Clock clock;
	sf::Time timeSinceLastUpdate = sf::Time::Zero;
	while (mWindow.isOpen())
	{
		sf::Time elapsedTime = clock.restart();
		timeSinceLastUpdate += elapsedTime;

			while (timeSinceLastUpdate > TimePerFrame)
			{
				timeSinceLastUpdate -= TimePerFrame;

				processEvents();
				update(TimePerFrame);
			}

		updateStatistic(elapsedTime);
		draw();
	}
}

void Game::update(sf::Time elapsedTime)
{
	mPlansza.update(elapsedTime);
}


void Game::processEvents()
{
	sf::Event ev;

	while(mWindow.pollEvent(ev))
	{
		switch (ev.type)
		{

		case sf::Event::Closed:
			mWindow.close();
			break;
		case sf::Event::KeyPressed:
			if(ev.key.code == sf::Keyboard::Escape)
				mWindow.close();
			mPlansza.mPlayer.KeyPressed(ev.key);
			break;
		case sf::Event::KeyReleased:
			mPlansza.mPlayer.KeyReleased(ev.key);
			break;
		default:
			break;
		}//switch
	}//while
}

void Game::draw()
{
	mWindow.clear(sf::Color(50,50,50,255));

	mPlansza.draw(&mWindow);

	mWindow.draw(mStatisticsText);
	mWindow.display();
}

void Game::updateStatistic(sf::Time elapsedTime)
{
	mStatisticsUpdateTime += elapsedTime;
	mStaticNumFrames += 1;

		if(mStatisticsUpdateTime > sf::seconds(1.0f))
		{
			mStatisticsText.setString("FPS: " + std::to_string(mStaticNumFrames));
			mStatisticsUpdateTime -= sf::seconds(1.0f);
			mStaticNumFrames = 0;
		}	
}